package org.iryshka.skyserver;

import java.io.File;

public class SkyRequest {
	
	public StringBuilder httpRequest = new StringBuilder(150);
	public String attributeGet;
	public String attributeExtension;
	
	public static File currentDir;
	
	public String selfAnalysis(SkyResponse skyResp){
		String httpRequestStr = new String(this.httpRequest);
		String helpStr = null;
		if (httpRequestStr.contains("GET")){
			helpStr = httpRequestStr.substring(httpRequestStr.indexOf("GET") + 4, httpRequestStr.indexOf("HTTP"));
			helpStr = helpStr.trim();
			if (helpStr.equals("/")){
				currentDir = SkyWebServer.serverDir;
				this.attributeGet = helpStr;
				this.findExtension(this.attributeGet);
				return "GET";
			}
			getCurrentDir(helpStr);
			helpStr = helpStr.substring(helpStr.lastIndexOf("/") + 1);
			helpStr = (helpStr.replace("20", " ")).replace("%", " ");
			
			this.attributeGet = helpStr.trim();
			this.findExtension(this.attributeGet);
			return "GET";
		}
		else if ((httpRequestStr.contains("POST")) || (httpRequestStr.contains("HEAD")) || (httpRequestStr.contains("DELETE"))){
			return skyResp.buildResponseHeader("405");
		}
		else{
			return skyResp.buildResponseHeader("400");
		}
	}
	
	private void getCurrentDir (String somePath){
		String helpStr = somePath.substring(0, somePath.lastIndexOf("/"));
		currentDir = new File(SkyWebServer.serverDir + helpStr);
	}
	
	private void findExtension(String attributeGet){
		if (attributeGet.contains(".")){
			this.attributeExtension = attributeGet.substring(attributeGet.lastIndexOf(".")+1);
		}
		if (attributeGet.equals("/")){
			this.attributeExtension = "html";
		}
	}
	
	public String hashMapAnalyze (){
		String str = HashMapExtension.myHashMap.get(this.attributeExtension);
		if (str == null){
			return "application/octet-stream";
		}
		else{
			return str;
		}
	}
}
